package cn.tedu._03vehicle.controller;

import cn.tedu._03vehicle.base.response.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/v1/file")
public class Uploadcontorller {
    /*
       文件上传功能
     */
    @PostMapping("/upload")
    public JsonResult upload(MultipartFile file) throws IOException {
        //1.获取文件名ww.jpg
        String filname = file.getOriginalFilename();
        //2.获取文件名后缀.jpg
        String suffix = filname.substring(filname.lastIndexOf("."));
        //3.处理文件名：全球唯一标识符
        filname = UUID.randomUUID() + suffix;
        //4.处理日期路径
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        String datePath = sdf.format(new Date());
        String StaticPath = "D:/files/";
        //5.创建保存文件的目录
        File dirFile = new File(StaticPath + datePath);
        if(!dirFile.exists()){
            dirFile.mkdirs();
        }
        //6.保存文件到服务器
        String filePath = StaticPath + datePath + filname;
        file.transferTo(new File(filePath));

        log.debug("全球唯一文件名：" + datePath);

        //前端工程师：获取图片在服务器中的路径，进行页面的图片回显
        return JsonResult.ok(datePath + filname);
    }
}
